package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [222024321072035/万能] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 无匹配路由，使用默认处理器
            handler = new DefaultHandler();
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: [222024321072035/万能] 如果连DefaultHandler都没有，返回500 Internal Server Error
            try {
                String error = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 25\r\n" +
                        "\r\n" +
                        "<h1>Server Error</h1>";
                response.write(error.getBytes(StandardCharsets.UTF_8));
                response.flush();
            } catch (Exception e) {
                // 忽略
            }
        }
    }
}
